package com.wzm.org.service.impl;


import com.wzm.basic.service.impl.BaseServiceImpl;
import com.wzm.org.domain.Department;
import com.wzm.org.mapper.DepartmentMapper;
import com.wzm.org.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 业务实现类：部门
 */
@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements DepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;

    @Transactional
    @Override
    public void add(Department department) {
        System.out.println(department); //看parent_id是多少
        //情况1：不选 -> parent_id=null
        //情况2：选了清空 -> parent_id=null
        //情况3：选上级部门 -> parent_id=6[上级部门]

        departmentMapper.save(department);

        //如果没有选中上级部门就加自己的id
        if(department.getParent_id()==null){
            department.setDirPath("/"+department.getId());
        }else{//如果选了上级部门
            //根据父id查询它的dirPath
            String parentDirPath = departmentMapper.loadById(department.getParent_id()).getDirPath();
            //再将父部门的dirPath与自己的id进行拼接
            department.setDirPath(parentDirPath+"/"+department.getId());
        }
        departmentMapper.update(department);
    }

    @Transactional
    @Override
    public void update(Department department) {

        //如果没有选中上级部门就加自己的id
        if(department.getParent_id()==null){
            department.setDirPath("/"+department.getId());
        }else{//如果选了上级部门
            //根据父id查询它的dirPath
            String parentDirPath = departmentMapper.loadById(department.getParent_id()).getDirPath();
            //再将父部门的dirPath与自己的id进行拼接
            department.setDirPath(parentDirPath+"/"+department.getId());
        }

        departmentMapper.update(department);
    }


    @Override
    public List<Department> deptTree() {
        List<Department> departments = departmentMapper.loadAll();
        Map<Long,Department> map = new HashMap<>();
        for (Department department : departments) {
            map.put(department.getId(),department);
        }

        List<Department> deptTree = new ArrayList<>();
        for (Department department : departments) {
            if(department.getParent_id() == null){//顶级部门
                deptTree.add(department);
            }else{//不是顶级部门
                //获取当前部门的上级部门id
                Long parent_id = department.getParent_id();
                //上级部门对象
                Department parentDepartment = map.get(parent_id);
                //将自己装在上级部门的集合中
                parentDepartment.getChildren().add(department);
            }
        }

        return deptTree;
    }
}
